package com.coolingme.sentinel;

import com.alibaba.csp.sentinel.cluster.flow.rule.ClusterFlowRuleManager;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.util.List;

/**
 * @author wangyue
 * @date 2022/10/30 19:47
 */
public class FlowRuleInitFunc implements InitFunc {
    private final String nacosAddress = "192.168.112.128:8848";
    private final String groupId      = "SENTINEL_GROUP";
    private final String dataIdSuffix = "-flow-rules";

    @Override
    public void init() throws Exception {
        ClusterFlowRuleManager.setPropertySupplier(namespace -> {
            ReadableDataSource<String, List<FlowRule>> flowRuleDs =
                    new NacosDataSource<>(nacosAddress, groupId, namespace + dataIdSuffix,
                            source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                            })
                    );
            return flowRuleDs.getProperty();
        });
    }
}
